package com.mall.cloud.controller;

import com.mall.cloud.bean.User;
import com.mall.cloud.common.CommonResult;
import com.mall.cloud.service.UserHystrixService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@RestController
@RequestMapping(produces = { "application/json;charset=UTF-8" })
public class UserHystrixController {
    @Autowired
    private UserHystrixService userHystrixService;

    @GetMapping("/testFallback/{id}")
    public CommonResult testFallback(@PathVariable Long id) {
        return userHystrixService.getUser(id);
    }

    @GetMapping("/testCommand/{id}")
    public CommonResult testCommand(@PathVariable Long id) {
        return userHystrixService.getUserCommand(id);
    }

    @GetMapping("/testException/{id}")
    public CommonResult testException(@PathVariable Long id) {
        return userHystrixService.getUserException(id);
    }

    @GetMapping("/testCache/{id}")
    public CommonResult testCache(@PathVariable Long id) {
        userHystrixService.getUserCache(id);
        userHystrixService.getUserCache(id);
        CommonResult userCache = userHystrixService.getUserCache(id);
        return CommonResult.success(userCache);
    }

    @GetMapping("/testRemoveCache/{id}")
    public CommonResult testRemoveCache(@PathVariable Long id) {
        userHystrixService.getUserCache(id);
        userHystrixService.removeCache(id);
        CommonResult userCache = userHystrixService.getUserCache(id);
        return CommonResult.success(userCache);
    }

    @GetMapping("/testList")
    public CommonResult testList() {
        return userHystrixService.testList();
    }

    @GetMapping("/testCollapser")
    public CommonResult testCollapser() throws ExecutionException, InterruptedException {
        Future<User> future1 = userHystrixService.getUserFuture(1L);
        Future<User> future2 = userHystrixService.getUserFuture(2L);
        User user1 = future1.get();
        User user2 = future2.get();
        Thread.sleep(200);
        Future<User> future3 = userHystrixService.getUserFuture(3L);
        User user3 = future3.get();
        List<User> users = new ArrayList<>();
        users.add(user1);
        users.add(user2);
        users.add(user3);
        return new CommonResult(users);
    }
}
